#include <iostream>
#include <ctime>
#include <unistd.h>
#include "RingQueue.hpp"
#include "Task.hpp"

void *Productor(void *args)
{
    RingQuene<Task> *rq = static_cast<RingQuene<Task> *>(args);
    while (true)
    {
        sleep(1);
        // 1.构造数据
        int x = rand() % 10 + 1; //[1,10]
        usleep(x*1000);
        int y = rand() % 10 + 1;
        Task t(x,y);
        // 2.生产 
        rq->Push(t);

        std::cout << "Productor -> " << t.debug() << std::endl;
    }
}

void *Consumer(void *args)
{
    RingQuene<Task> *rq = static_cast<RingQuene<Task> *>(args);
    while(true)
    {
        //1.消费数据
        Task t;
        rq->Pop(&t);
        t();
        //2.处理数据
        std::cout << "Consumer -> " << t.result() << std::endl;
    }
}

int main()
{
    srand(time(nullptr) ^ getpid());
    RingQuene<Task> *rq = new RingQuene<Task>(5);
    pthread_t p1,p2,c1,c2,c3;
    pthread_create(&p1, nullptr, Productor, (void *)rq);
    pthread_create(&p2, nullptr, Productor, (void *)rq);
    pthread_create(&c1, nullptr, Consumer, (void *)rq);
    pthread_create(&c2, nullptr, Consumer, (void *)rq);
    pthread_create(&c3, nullptr, Consumer, (void *)rq);

    pthread_join(c1, nullptr);
    pthread_join(c2, nullptr);
    pthread_join(c3, nullptr);
    pthread_join(p1, nullptr);
    pthread_join(p2, nullptr);

    return 0;
}
